﻿using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Trentacular.SharePoint.Deployment.Model;
using Trentacular.SharePoint.Deployment.Util;

namespace Trentacular.SharePoint.Deployment.Data.Proxy
{
    public class WebApplicationFeaturesLazyInitializer : BaseDomainListLazyInitializer<WebApplication, WebApplicationFeature>
    {
        protected override object InitializeTarget()
        {
            var spFarm = SPFarm.Local;
            var service = spFarm.Services.GetValue<SPWebService>("");
            var spWebApp = service.WebApplications[Owner.Id];

            var activatedFeatures = spWebApp.Features.Cast<SPFeature>()
                .Select(f => f.DefinitionId)
                .ToList();

            return Owner.AvailableFeatureDefinitions
                .Where(fd => fd.Scope == SPFeatureScope.WebApplication)
                .Select(fd => new WebApplicationFeature
                    {
                        Definition = fd,
                        Parent = Owner,
                        Activated = activatedFeatures.Contains(fd.Id)
                    })
                .ToVirtualList();
        }
    }
}
